/*
    The MIT License (MIT)

    Copyright (c) 2016 fatal_error

    Permission is hereby granted, free of charge, to any person obtaining a copy of
    this software and associated documentation files (the "Software"), to deal in
    the Software without restriction, including without limitation the rights to
    use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
    the Software, and to permit persons to whom the Software is furnished to do so,
    subject to the following conditions:

    The above copyright notice and this permission notice shall be included in all
    copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
    FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
    COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
    IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
;(function($){
	$.fn.datetimepicker.dates['zh-CN'] = {
			days: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"],
			daysShort: ["周日", "周一", "周二", "周三", "周四", "周五", "周六", "周日"],
			daysMin:  ["日", "一", "二", "三", "四", "五", "六", "日"],
			months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			monthsShort: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
			today: "今天",
			suffix: [],
			meridiem: ["上午", "下午"]
	};
}(jQuery));

var dollar = $.noConflict();

var DataSource = (function(){
    function DataSource(frequency){
        this.xhr = new XMLHttpRequest();
        if(typeof(frequency) === "number" && frequency >= 0){
            this.frequency = frequency;
        }
    }

    DataSource.prototype = {
        timeStamp: [],
        temperature: [],
        sunlight: [],
        flame: [],
        gases: [],
        human: [],
        timeoutId: 0,
        frequency: 2000,
        tail: -1,
        stopped: true,
        xhr: null

    };

    DataSource.prototype.fetch = function(start, end, count, callback){
    	if(this.stopped){
    		return;
    	}
        this.xhr = new XMLHttpRequest();
        var instant = this;
        this.xhr.onreadystatechange = function(){
            if(instant.xhr.readyState === 4){
                var rep = instant.xhr.responseText;
                if(rep !== 'E'){
                    rep = eval('(' + rep + ')');
                    instant.addRecords(rep);
                }
                instant.timeoutId = setTimeout(callback, instant.frequency); 
            }
        };
        if(count < 0){
            this.xhr.open("GET", '/data/iquery_' + start + '_' + end + '_' + -count);
        }else{
            this.xhr.open("GET", '/data/query_' + start + '_' + end + '_' + count);
        }
        this.xhr.send(null);
    };

    DataSource.prototype.start = function() {
    	this.stopped = false;
        var instant = this;
        var ts = 0;
        if(this.tail >= 0){
            ts = this.timeStamp[this.tail];
        }
        this.fetch(ts, 0, -10, function(){
            instant.start();
        });
    };

    DataSource.prototype.stop = function(){
    	this.stopped = true;
        clearTimeout(this.timeoutId);
        this.xhr.abort();
    };

    DataSource.prototype.changeFrequency = function(freq){
        this.stop();
        var instant = this;
        setTimeout(function(){
        	instant.frequency = freq;
        	instant.start();
        }, 200);
    };

    DataSource.prototype.slice = function(start, end) {
        return {
            temperature: this.temperature.slice(start, end),
            sunlight: this.sunlight.slice(start, end),
            flame: this.sunlight.slice(start, end),
            gases: this.gases.slice(start, end),
            human: this.human.slice(start, end),
            timeStamp: this.timeStamp.slice(start, end)
        };
    };

    DataSource.prototype.fresh = function(count){
        if(count == 1){
            return {
                temperature: this.temperature[this.temperature.length - 1],
                sunlight: this.sunlight[this.sunlight.length - 1],
                flame: this.flame[this.flame.length - 1],
                gases: this.gases[this.gases.length - 1],
                human: this.human[this.human.length - 1],
                timeStamp: this.timeStamp[this.timeStamp.length - 1]
            };
        }
        return this.slice(-count);
    };

    DataSource.prototype.after = function(start, count){
        var index = 0;
        while(index < this.timeStamp.length && this.timeStamp[index] <= start){
            index++;
        }
        if(index >= this.timeStamp.length){
            return null;
        }
        return this.slice(index, index + count);
    };

    DataSource.prototype.before = function(end, count){
        var index = this.timeStamp.length - 1;
        while(this.timeStamp[index] > end && index >= 0){
            index--;
        }
        if(index < 0){
            return null;
        }
        return this.slice(index - count, index);
    };

    DataSource.prototype.between = function(start, end){
        var p = 0, r = this.timeStamp.length - 1;
        while(p < this.timeStamp.length && this.timeStamp[p] <= start){
            p++;
        }
        if(p === this.timeStamp.length){
            return;
        }

        while(r >= 0 && this.timeStamp[r] > end){
            r--;
            if(this.timeStamp[r] < end){
                r++;
                break;
            }
        }
        if(r < 0){
            return;
        }

        return this.slice(p, r);
    };

    DataSource.prototype.arrayDescription = function() {
        return this.timeStamp.toString();
    };

    DataSource.prototype.addRecords = function(src){
        // do something.
        for(var i = 0; i < src.timeStamp.length; i++){
            var _temperature = src.temperature[i],
                _flame = src.flame[i],
                _sunlight = src.sunlight[i],
                _gases = src.gases[i],
                _human = src.human[i],
                _timeStamp = src.timeStamp[i];
            if(this.tail === -1 || _timeStamp > this.timeStamp[this.tail]){
                this.timeStamp.push(_timeStamp);
                this.temperature.push(_temperature);
                this.sunlight.push(_sunlight);
                this.flame.push(_flame);
                this.human.push(_human);
                this.gases.push(_gases);
                this.tail++;
            }else if(_timeStamp < this.timeStamp[0]){
                quickUnshift(this.timeStamp, _timeStamp);
                quickUnshift(this.temperature, _temperature);
                quickUnshift(this.flame, _flame);
                quickUnshift(this.sunlight, _sunlight);
                quickUnshift(this.gases, _gases);
                quickUnshift(this.human, _human);
                this.tail++;
            }else{
            	// push + sort.
            	
            }
        }
    };

    DataSource.prototype.sort = function(){
    	function qswap(A, x, y){
    		var t = A[x];
    		A[x] = A[y];
    		A[y] = t;
    	}

        function swap(instant, i, j){
            qswap(instant.timeStamp, i, j);
            qswap(instant.temperature, i, j);
            qswap(instant.sunlight, i, j);
            qswap(instant.flame, i, j);
            qswap(instant.gases, i, j);
            qswap(instant.human, i, j);
        }

        var stack = [];
        stack.push({p: 0, r: this.timeStamp.length - 1});
        while(stack.length > 0){
            var current = stack.pop();
            if(current.p < current.r){
                var q = current.p - 1;
                for(var i = current.p; i < current.r; i++){
                    if(this.timeStamp[i] <= this.timeStamp[current.r]){
                        q++;
                        swap(this, i, q);
                    }
                }
                q++;
                swap(this, q, current.r);
                stack.push({p: current.p, r: q-1});
                stack.push({p: q+1, r: current.r});
            }
        }
    };

    return DataSource;
})();

var ChartView = (function(){
    function ChartView(name, label, fc, sc, pc){
        this.timeStamps = [];
        this.context = document.getElementById(name).getContext("2d");
        this.data.datasets[0].label = label;
        this.data.datasets[0].fillColor = fc;
        this.data.datasets[0].strokeColor = sc;
        this.data.datasets[0].pointColor = pc;
        this.chart = new Chart(this.context).Line(this.data, this.options);
    }

    ChartView.prototype = {
        context: null,
        chart: null,
        data: {
            labels: [],
            datasets: [
                {
                    label: null,
                    fillColor: "rgba(220,220,220,0.2)",
                    strokeColor: "rgba(220,220,220,1)",
                    pointColor: "rgba(220,220,220,1)",
                    pointStrokeColor: "#fff",
                    pointHighlightFill: "#fff",
                    pointHighlightStroke: "rgba(220,220,220,1)",
                    data: []
                }
            ]
        },
        options: {
            responsive: true,
            scaleBeginAtZero: false,
            animationSteps: 24,
            bezierCurve: false
        },
        timeStamps: null
    };

    ChartView.prototype.appendData = function(data, timeStamp){
        if(this.timeStamps.length !== 0 && timeStamp <= this.timeStamps[this.timeStamps.length - 1]){
            return;
        }
        if(this.timeStamps.length >= 10){
            this.chart.removeData();
            this.timeStamps.shift();
        }
        this.timeStamps.push(timeStamp);
        var date = new Date();
        date.setTime(timeStamp);
        var label = date.toLocaleTimeString();
        if(label.slice(0, 2) === '上午'){
            label = label.slice(2) + ' am';
        }else{
            label = label.slice(2) + ' pm';
        }
        this.chart.addData([data], label);
    };

    ChartView.prototype.shut = function(){
        this.chart.stop();
        this.chart.clear();
        this.chart.destroy();
    };

    return ChartView;
})();

var CirclePanelView = (function(){
    function CirclePanelView(name, minValue, maxValue, minColor, maxColor, unit, animation) {
        this.name = name;
        this.unit = unit;
        this.noAnimation = !animation;
        canvasObj = document.getElementById(name);
        this.context = canvasObj.getContext("2d");
        this.contextHeight = canvasObj.height;
        this.contextWidth = canvasObj.width;
        this.radius = this.contextWidth / 2;
        if(this.contextWidth > this.contextHeight){
            this.radius = this.contextHeight / 2;
        }
        this.innerradius = this.radius * 0.9;
        this.centerX = this.contextWidth / 2;
        this.centerY = this.contextHeight / 2;

        this.minRGB = this.getRGB(minColor);
        this.maxRGB = this.getRGB(maxColor);
        this.minValue = minValue;
        this.maxValue = maxValue;
    }

    CirclePanelView.prototype = {
        name : null,
        context : null,
        contextHeight: 0,
        contextWidth: 0,
        noAnimation: false,

        minValue : 0,
        maxValue : 100,
        minRGB : null,
        maxRGB : null,

        current : 0,
        value: 0,
        delta: 1.0,

        radius: 0,
        innerradius: 0,
        centerX : 0,
        centerY : 0,
        unit : '',
        raf: null,
        fillTextMethod: null
    };

    CirclePanelView.prototype.getRGB = function(color){
        return {
           r: parseInt(color.substr(1,2), 16),
           g: parseInt(color.substr(3,2), 16),
           b: parseInt(color.substr(5,2), 16)
        };
    };

    CirclePanelView.prototype.getColorString = function(obj){
        obj.r = Math.round(obj.r);
        obj.g = Math.round(obj.g);
        obj.b = Math.round(obj.b);
        var color = '#';
        color += (obj.r < 16 ? '0':'') + obj.r.toString(16);
        color += (obj.g < 16 ? '0':'') + obj.g.toString(16);
        color += (obj.b < 16 ? '0':'') + obj.b.toString(16);
    
        return color;
    };

    CirclePanelView.prototype.drawPanel = function() {
    	var rate = this.current / (this.maxValue - this.minValue);
        var angle = rate * Math.PI * 2 - Math.PI / 2;
        if(angle < 0){
        	angle = Math.PI * 2 + angle;
        }
        var translatex = this.centerx + Math.cos(angle) * this.innerradius;
        var translatey = this.centery + Math.sin(angle) * this.innerradius;

        this.context.beginPath();
        this.context.arc(this.centerX, this.centerY, this.radius, Math.PI * 2, 0, false);
        this.context.fillStyle = "lightgrey";
        this.context.fill();
        this.context.save();

        this.context.beginPath();
        this.context.arc(this.centerX, this.centerY, this.innerradius, Math.PI * 2, 0, false);
        this.context.fillStyle = "white";
        this.context.fill();
        this.context.save();

        this.context.fillStyle = this.getColorString({
        	r: Math.round((this.maxRGB.r - this.minRGB.r) * rate + this.minRGB.r),
        	g: Math.round((this.maxRGB.g - this.minRGB.g) * rate + this.minRGB.g),
        	b: Math.round((this.maxRGB.b - this.minRGB.b) * rate + this.minRGB.b),
        });
        this.context.beginPath();
        this.context.arc(this.centerX, this.centerY, this.radius, Math.PI * 1.5, angle, false);
        this.context.lineTo(translatex, translatey);
        this.context.arc(this.centerX, this.centerY, this.innerradius, angle, Math.PI * 1.5, true);
        this.context.closePath();
        this.context.fill();
        this.context.save();
        if(this.fillTextMethod){
        	this.fillTextMethod(this);
        }else{
	        this.context.textAlign = "center";
	        this.context.font = "24px 'Apple Pingfang' 'Microsoft Yahei' sans-serif";
	        this.context.fillText((Math.round(this.current*10)/10).toString() + this.unit, this.centerX, this.centerY+13);
    	}
    };

    CirclePanelView.prototype.setValue = function(x) {
        if(x >= this.minValue && x <= this.maxValue) {
            this.value = x;
            this.delta = (this.value - this.current) / 24.0;
            this.renderFrame(this);
        }
    };

    CirclePanelView.prototype.renderFrame = function(i) {
        if((i.delta > 0 && i.current >= i.value) || (i.delta < 0 && i.current <= i.value) || i.noAnimation) {
            i.current = i.value;
            i.clear();
            i.drawPanel();
            return;
        }
        i.clear();
        i.current += i.delta;
        i.drawPanel();
        var func = function() {
            i.renderFrame(i);
        };
        if(!requestAnimationFrame){
        	i.raf = setTimeout(func, 1000/60);
        }else {
        	i.raf = requestAnimationFrame(func);
        }
    };

    CirclePanelView.prototype.stopAnimating = function(){
        if(!requestAnimationFrame){
            clearTimeout(this.raf);
        }else{
            cancelAnimationFrame(this.raf);
        }
    };

    CirclePanelView.prototype.clear = function(){
        this.stopAnimating();
        this.context.clearRect(0, 0, this.contextWidth, this.contextHeight);
    };

    CirclePanelView.prototype.shut = function(){
    	this.clear();
    };

    return CirclePanelView;
})();

var TableView = (function(){
    function TableView(name, datasrc){
        // do something.
        this.domElement = document.getElementById(name);
        this.dataSource = datasrc;
    }

    TableView.prototype = {
        domElement: null,
        dataSource: null,
        currentDisplaying: null
    };

    TableView.prototype.clear = function(){
    	while(this.domElement.rows.length > 1){
    		this.domElement.deleteRow(this.domElement.rows.length - 1);
    	}
    };

    TableView.prototype.displayLatestStatistic = function(){
    	if(!this.dataSource){
    		return;
    	}
    	this.currentDisplaying = this.dataSource.fresh(10);
    	this.renderTable();
    };

    TableView.prototype.displayStatisticBetween = function(start, end){
    	if(!this.dataSource){
    		return;
    	}
    	this.currentDisplaying = this.dataSource.between(start, end);
    	this.renderTable();
    };

    TableView.prototype.pushRow = function(item){
    	var i = 0;
   		var newrow = this.domElement.insertRow(1);
    	for(i = 0; i < 5; i++){
        	newrow.insertCell();
        	newrow.cells[i].innerHTML = item[i];
    	}
    };

    TableView.prototype.renderTable = function(){
    	this.clear();
    	for(var i = 0; i < this.currentDisplaying.timeStamp.length; i++){
    		var ts = this.currentDisplaying.timeStamp[i],
    			tem = this.currentDisplaying.temperature[i],
    			lt = this.currentDisplaying.sunlight[i],
    			gas = this.currentDisplaying.gases[i],
    			flm = this.currentDisplaying.flame[i];
    		var date = new Date();
    		date.setTime(ts * 1000);
    		ts = date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    		this.pushRow([ts, tem, lt, flm, gas]);
    	}
    };

    return TableView;
})();

var SettingPanel = (function(){
    function SettingPanel(navClass, liClass, switcherClass){
        // do something.
        if(navClass[0] !== '.'){
        	navClass = '.' + navClass;
        }
        if(liClass[0] !== '.'){
        	liClass = '.' + liClass;
        }
        if(switcherClass[0] !== '.'){
            switcherClass = '.' + switcherClass;
        }
        this.domElement = document.querySelector(navClass);
        this.list = document.querySelectorAll(liClass);
        this.switchers = document.querySelectorAll(switcherClass);
        for(var i = 0; i < this.switchers.length; i++){
            var instant = this;
        	this.switchers[i].onclick = function(){
        		instant.toggle();
        	};
        }
    }

    SettingPanel.prototype = {
        domElement: null,
        list: null,
        animate: true,
        hidden: true,
        switchers: null
    };

    SettingPanel.prototype.show = function(){
        // do something.
        this.hidden = false;
        if(!this.animate){
        	this.domElement.style.opacity = "1";
        	this.domElement.style.scale = "1";
        	for(var i = 0; i < this.list.length; i++){
        		this.list[i].style.opacity = "1";
        	}
        	return;
        }
        dynamics.animate(this.domElement, {
        	opacity: 1,
        	scale: 1
        }, {
        	type: dynamics.easeInOut,
        	friction: 80,
        	duration: 200
        });
        for(var i = 0; i < this.list.length; i++){
            var item = this.list[i];
            dynamics.css(item,{
                opacity: 0,
                translateY: 20
            });
            dynamics.animate(item,{
                opacity: 1,
                translateY: 0
            },{
                type: dynamics.spring,
                frequency: 300,
                friction: 435,
                duration: 1000,
                delay: 100 + i * 40
            });
        }
    };

    SettingPanel.prototype.hide = function(){
        // do something.
        if(this.hidden){
        	return;
        }
        if(!this.animate){
        	this.domElement.style.opacity = "0";
        	this.domElement.style.scale = "0.1";
        }

        this.hidden = true;
        dynamics.animate(this.domElement, {
        	opacity: 0,
        	scale: 0.1
        }, {
        	type: dynamics.easeInOut,
        	friction: 80, 
        	duration: 200
        });
    };

    SettingPanel.prototype.toggle = function(){
        // do something.
        if(this.hidden){
        	this.show();
        }else{
        	this.hide();
        }
    };

    return SettingPanel;
})();

var AlertView = (function(){
	function AlertView(name){
		this.queryElement = dollar(name);
		this.domElement = document.querySelector(name);
	}

	AlertView.prototype = {
		queryElement: null,
		domElement: null,
		hidden: true
	};

	AlertView.prototype.show = function(){
		this.hidden = false;
		dynamics.animate(this.domElement, {
			opacity: 1,
			scale: 1
		}, {
			type: dynamics.easeInOut,
			duration: 400,
			friction: 80
		});
	};

	AlertView.prototype.hide = function(){
		this.hidden = true;
		dynamics.animate(this.domElement, {
			opacity: 0,
			scale: 0.1
		}, {
			type: dynamics.easeInOut,
			duration: 400,
			friction: 80
		});
	};

	AlertView.prototype.danger = function(x){
		this.queryElement.removeClass("alert-success");
		this.queryElement.addClass("alert-danger");
		this.queryElement.text(x);
	};

	AlertView.prototype.safe = function(x){
		this.queryElement.removeClass("alert-danger");
		this.queryElement.addClass("alert-success");
		this.queryElement.text(x);
	};

	return AlertView;
})();

var ViewController = (function(){
    function ViewController(datasrc){
        if(window.devicePixelRatio > 1){
            this.retina = true;
        }
        this.dataSource = datasrc;
        this.configPanels();
        this.human = new AlertView("#hsa");
        this.human.show();
        this.refreshView();
    }

    ViewController.prototype = {
    	isChartView: false,
        charts: [],
        panels: [],
        temperatureChart: null,
        flameChart: null,
        sunlightChart: null,
        gasesChart: null,
        temperaturePanel: null,
        sunlightPanel: null,
        gasesPanel: null,
        flamePanel: null,
        human: null,

        dataSource: null,
        timeoutId: 0,
        frequency: 1000,
        retina: false,
        stopped: false
    };

    ViewController.prototype.configPanels = function(){
        if(this.retina){
            dollar("canvas").attr("height", "300");
            dollar("canvas").attr("width", "300");
        }else{
            dollar("canvas").attr("height", "150");
            dollar("canvas").attr("width", "150");
        }
    	this.panels[0] = new CirclePanelView("temperature", 0, 60, '#ADD8E6', '#8B0000', '℃', true);
		this.panels[1] = new CirclePanelView("sunlight", 0, 300, '#2F4F4F', '#FFFF00', 'Lx', true);
		this.panels[2] = new CirclePanelView("flame", 0, 1024, '#008B8B', '#FF0000', '%', true);
		this.panels[3] = new CirclePanelView("gases", 0, 1024, '#90EE90', '#111111', '%', true);

		this.temperaturePanel = this.panels[0];
		this.sunlightPanel = this.panels[1];
		this.flamePanel = this.panels[2];
		this.gasesPanel = this.panels[3];

		this.gasesPanel.fillTextMethod = function(instant){
			instant.context.textAlign = "center";
	        instant.context.font = "24px 'Apple Pingfang' 'Microsoft Yahei' sans-serif";
	        if(instant.current < 256){
	        	instant.context.fillText("优", instant.centerX, instant.centerY + 13);
	        }else if(instant.current < 512){
	        	instant.context.fillText("良", instant.centerX, instant.centerY + 13);
	        }else if(instant.current < 768){
	        	instant.context.fillText("中", instant.centerX, instant.centerY + 13);
	        }else{
	        	instant.context.fillText("差", instant.centerX, instant.centerY + 13);
	        }
		};

		this.flamePanel.fillTextMethod = function(instant){
			instant.context.textAlign = "center";
			instant.context.font = "24px 'Apple Pingfang' 'Microsoft Yahei' sans-serif";
			if(instant.current < 30){
				instant.context.fillText("安全", instant.centerX, instant.centerY + 13);
			}else if(instant.current < 100){
				instant.context.fillText("可疑", instant.centerX, instant.centerY + 13);
			}else if(instant.current < 300){
				instant.context.fillText("危险", instant.centerX, instant.centerY + 13);
			}else if(instant.current < 600){
				instant.context.fillText("极度危险", instant.centerX, instant.centerY + 13);
			}else{
                instant.context.fillText("火灾", instant.centerX, instant.centerY + 13);
            }
		};
    };

    ViewController.prototype.configCharts = function(){
    	this.charts[0] = new ChartView("temperature", '温度', '#BAE4F5', '#87CEEB', '#87CEEB');
		this.charts[1] = new ChartView("sunlight", '光照', '#FDE68E', 'FFCA00', 'FFCA00');
		this.charts[2] = new ChartView("flame", '火焰', '#F18C8C', '#8B0000', '#8B0000');
		this.charts[3] = new ChartView("gases", '空气', '#AAE8E8', '#008B8B', '#008B8B');
        this.temperatureChart = this.charts[0];
        this.sunlightChart = this.charts[1];
        this.flameChart = this.charts[2];
		this.gasesChart = this.charts[3];
    };

    ViewController.prototype.clear = function(){
        this.stop();
    	if(this.isChartView){
    		for(var i = 0; i < this.charts.length; i++){
    			this.charts[i].shut();
    			this.charts[i] = null;
    		}
    		this.temperatureChart = this.sunlightChart = this.flameChart = this.gasesChart = null;
    	}else{
    		for(var i = 0; i < this.panels.length; i++){
    			this.panels[i].shut();
    			this.panels[i] = null;
    		}
    		this.temperaturePanel = this.sunlightPanel = this.flamePanel = this.gasesPanel = null;
    	}
    };

    ViewController.prototype.switchView = function(){
        this.clear();
        if(this.isChartView){
            document.getElementById("switchview").innerHTML = '切换到图表';
            document.getElementById("viewtitle1").innerHTML = '仪表盘 <span class="sr-only">(current)</span>';
            document.getElementById("viewtitle2").innerHTML = '仪表盘';

        	dollar(".col-xs-12").attr("class", "col-xs-6 col-md-3");
            dollar("canvas").attr("class", "panel");
            this.configPanels();
        }else{
            document.getElementById("switchview").innerHTML = '切换到仪表盘';
            document.getElementById("viewtitle1").innerHTML = '图表 <span class="sr-only">(current)</span>';
            document.getElementById("viewtitle2").innerHTML = '图表';

            dollar("canvas").attr("class", "");
            dollar(".col-xs-6").attr("class", "col-xs-12 col-md-5");
            this.configCharts();
        }
        this.isChartView = !this.isChartView;
        this.refreshView();
    };

    ViewController.prototype.refreshView = function(){
    	this.stopped = false;
        if(this.isChartView){
        	var data = this.dataSource.fresh(10);
            if(data){
                for(var i = 0; i < data.timeStamp.length; i++){
                    var _temperature = data.temperature[i],
                        _sunlight = data.sunlight[i],
                        _flame = data.flame[i],
                        _gases = data.gases[i],
                        _timeStamp = data.timeStamp[i];
                    this.temperatureChart.appendData(_temperature, _timeStamp * 1000);
                    this.sunlightChart.appendData(_sunlight, _timeStamp * 1000);
                    this.flameChart.appendData(_flame, _timeStamp * 1000);
                    this.gasesChart.appendData(_gases, _timeStamp * 1000);
                }
                var _human = data.human.pop();
                if(_human){
                	this.human.danger("有人在附近！");
                }else{
                	this.human.safe("附近没有人。")
                }
            }
        }else{
        	var data = this.dataSource.fresh(1);
            if(data){
                this.temperaturePanel.setValue(data.temperature);
                this.sunlightPanel.setValue(data.sunlight);
                this.flamePanel.setValue(data.flame);
                this.gasesPanel.setValue(data.gases);
                if(data.human){
                	this.human.danger("有人在附近！");
                }else{
                	this.human.safe("附近没有人。")
                }
            }
        }

        var instant = this;
        this.timeoutId = setTimeout(function(){
        	instant.refreshView();
        }, this.frequency);
    };

    ViewController.prototype.stop = function(){
    	this.stopped = true;
        clearTimeout(this.timeoutId);
    };

    ViewController.prototype.changeFrequency = function(value){
    	this.stop();
    	this.frequency = value;
    	this.refreshView();
    };

    return ViewController;
})();

window.onload = function(){
    window.dataSource = new DataSource(2000);
    window.dataSource.start();
    window.tableView = new TableView("datatable", window.dataSource);
    window.settingPanel = new SettingPanel("popovernav", "popoverli", "settingpanelbtn");
    window.vc = new ViewController(window.dataSource);
    window.hsaOn = true;
    document.getElementById("switchview").onclick = function(){
    	window.vc.switchView();
    };

    document.getElementById("pausedownload").onclick = function(){
    	if(window.dataSource.stopped){
    		document.getElementById("pausedownload").innerHTML = "暂停下载数据";
    		window.dataSource.start();
    	}else{
    		document.getElementById("pausedownload").innerHTML = "开始下载数据";
    		window.dataSource.stop();
    	}
    };

    document.getElementById("pauserefresh").onclick = function(){
    	if(window.vc.stopped){
    		document.getElementById("pauserefresh").innerHTML = "暂停刷新数据";
    		window.vc.refreshView();
    	}else{
    		document.getElementById("pauserefresh").innerHTML = "开始刷新数据";
    		window.vc.stop();
    	}
    };

    document.getElementById("refreshtable").onclick = function(){
    	window.tableView.displayLatestStatistic();
    };

    document.getElementById("displayhsa").onclick = function(){
    	if(window.hsaOn){
    		document.getElementById("displayhsa").innerHTML = "隐藏人类传感器状态";
    		window.vc.human.show();
    	}else{
    		document.getElementById("displayhsa").innerHTML = "显示人类传感器状态";
    		window.vc.human.hide();
    	}
    	window.hsaOn = !window.hsaOn;
    };

	window.slider = new Slider('#ex1', {
		formatter: function(value) {
			return value.toString() + '秒';
		}
	});
	window.slider.on("slideStop", function(value) {
		window.vc.changeFrequency(value * 1000);
		window.dataSource.changeFrequency(value * 1000);
	});
	window.datetimepicker = dollar('#datetimepicker').datetimepicker({language: 'zh-CN'});
    setTimeout(function(){window.tableView.displayLatestStatistic();}, 1500);
};
